<template>
    <t-space direction="vertical" size="large" class="tdesign-demo-form-status">
        {{ isShowUP }}

        <t-form ref="formValidatorStatus" :data="shop" :rules="rules" @reset="onReset" @submit="onSubmit"
            @validate="onValidate">
            <t-form-item label="商品名称" name="name">
                <t-input v-model="shop.name" placeholder="请输入商品名称"></t-input>
            </t-form-item>

            <t-form-item label="商品图片" name="imgUrl">
                <t-input v-model="shop.imgUrl" placeholder="请输入商品分类" hidden></t-input>
                <template v-if="isShowUP">
                    <t-upload name="file" v-model="file" method="post" action="/api/img/upload2" theme="image"
                        tips="请选择单张图片文件上传" draggable=true @fail="formatResponse" @success="imgSUC" :data="{ id: 1 }"
                        @format-response="formatResponse"></t-upload>
                </template>
            </t-form-item>
            <t-form-item label="商品价格" name="price">
                <t-input v-model="shop.price" placeholder="请输入商品价格"></t-input>
            </t-form-item>
            <t-form-item label="商品分类" name="fenlei">
                <t-input v-model="shop.fenlei" placeholder="请输入商品分类"></t-input>
            </t-form-item>
            <t-form-item label="商品标签" name="label">
                <t-check-tag shape="round" v-for="(tag, index) in label" :key="index" style="margin-left:7px;"
                    :default-checked="tag.defaultChecked" :checked="shop.label.some(n => n.id == tag.id)"
                    :disabled="!!tag.disabled" @click="handleClick(tag, index)" @change="handleChange">
                    {{ tag.text }}
                </t-check-tag>
                <t-input v-model="shop.label" hidden placeholder="请输入商品分类"></t-input>
            </t-form-item>
            <t-form-item :status-icon="false">
                <t-space size="small">
                    <t-button theme="primary" type="submit">提交</t-button>
                    <t-button theme="default" variant="base" type="reset">重置</t-button>
                </t-space>
            </t-form-item>
        </t-form>
    </t-space>
</template>
<script lang="jsx" setup>
import { ref, onMounted, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { addNewFood } from '@/http/modules/store';
import { getFoodlabelData } from '@/http/modules/store'
import mitt from '@/utils/mitt/index'
import useShopInfo from '@/store/modules/shopInfo.js';
const getShopInfo = useShopInfo();

const handleClick = (tag, index) => {
    // console.log(tag, index, '修改了', shop.value.label);
    if (shop.value.label.some(n => n.id == tag.id)) {
        const i = shop.value.label.findIndex(n => n.id == tag.id);
        shop.value.label.splice(i, 1);
    } else {
        shop.value.label.push(tag)
    }
};

const handleChange = (isChecked) => {
    console.log(isChecked);
};

const isShowUP = ref(false);

const label = ref();
getFoodlabelData().then(res => {
    label.value = res
})
const shop = ref({
    _id: new Date().getTime() + Math.floor(Math.random()) * 11,
    shopid: '',
    name: '',
    price: '',
    fenlei: "",
    imgUrl: "",
    label: []
})

// const shopCoputed = computed(() => {
//     return {
//         ...shop.value,
//         label: shop.value.label.map(n => n.id)
//     }
// })

const shopComputed = computed(() => {
    return {
        ...shop.value,
        shopid: getShopInfo.shopInfo.id,
        label: shop.value.label.map(n => n.id)
    }
})
mitt.on('isShowUP', (bol) => {
    isShowUP.value = bol;
})

const priceCheck = (val) => {
    if (isNaN(Number(val))) {
        return { result: false, message: '请输入数字', type: 'error' };
    }
    return { result: true, message: '', type: 'success' };
};

const labelCheck = (val) => {
    if (val.length == 0) {
        return { result: false, message: '请加入至少一个标签', type: 'error' };
    }
    return { result: true, message: '', type: 'success' };
};

const rules = {
    name: [
        { required: true, message: '商品名称必填', type: 'error' },
        {
            min: 2,
            message: '商品名称至少需要两个字',
            type: 'error',
            trigger: 'blur',
        },
    ],
    price: [
        { required: true, message: '价格必填', type: 'error' },
        { validator: priceCheck }
    ],
    fenlei: [
        { required: true, message: '商品分类必填', type: 'error' },
    ],
    imgUrl: [
        { required: true, message: '必须上传图片', type: 'error' },
    ],
    label: [
        { validator: labelCheck }
    ]
};

const onSubmit = ({ validateResult, firstError, e }) => {
    e.preventDefault();
    if (validateResult === true) {
        addNewFood(shopComputed.value).then(res => {
            console.log('上传商品成功！', res);
        })
        mitt.emit("updateFood")
        mitt.emit("closeChouTi")

        MessagePlugin.success(`提交商品${shop.value.name}成功`);
        shop.value = {
            _id: '',
            shopid: '',
            name: '',
            price: '',
            fenlei: "",
            imgUrl: "",
            label: []
        }
        file.value = []
    } else {
        console.log('Validate Errors: ', firstError, validateResult);
        MessagePlugin.warning(firstError);
    }
};

const file = ref([]);

const imgSUC = (c) => {
    shop.value.imgUrl = c.response.imageUrl
    file[0].url = { name: shop.value.name || '商品图片', url: c.response.imageUrl }
}
const onReset = () => {
    shop.value = {
        _id: '',
        shopid: '',
        name: '',
        price: '',
        fenlei: "",
        imgUrl: "",
        label: []
    }
    MessagePlugin.success('重置成功');
};


</script>
<style>
.tdesign-demo-form-status .t-input {
    width: 520px;
}
</style>
  